<template>
  <div class="order-list-container">
    <div class="page-header">
      <h2>订单管理</h2>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-input
        v-model="searchForm.orderNo"
        placeholder="请输入订单编号"
        style="width: 200px; margin-right: 10px;"
        clearable
      />
      <el-select
        v-model="searchForm.state"
        placeholder="请选择订单状态"
        style="width: 150px; margin-right: 10px;"
        clearable
      >
        <el-option label="待支付" value="待支付" />
        <el-option label="已支付" value="已支付" />
        <el-option label="已发货" value="已发货" />
        <el-option label="已完成" value="已完成" />
        <el-option label="已取消" value="已取消" />
      </el-select>
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 250px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 订单列表 -->
    <el-table :data="orderList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="订单ID" width="80" />
      <el-table-column prop="orderNo" label="订单编号" width="180" />
      <el-table-column prop="totalPrice" label="订单金额" width="120">
        <template #default="scope">
          ¥{{ scope.row.totalPrice }}
        </template>
      </el-table-column>
      <el-table-column prop="userId" label="用户ID" width="100" />
      <el-table-column prop="linkUser" label="联系人" width="120" />
      <el-table-column prop="linkPhone" label="联系电话" width="150" />
      <el-table-column prop="linkAddress" label="联系地址" :show-overflow-tooltip="true" />
      <el-table-column prop="state" label="订单状态" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.state)">{{ scope.row.state }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="viewOrderDetail(scope.row)">查看详情</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="orderList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div v-if="currentOrder">
        <div class="order-detail-info">
          <h3>订单基本信息</h3>
          <el-descriptions border column="2" :column="{ xs: 1, sm: 2 }">
            <el-descriptions-item label="订单ID">{{ currentOrder.id }}</el-descriptions-item>
            <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="订单金额">¥{{ currentOrder.totalPrice }}</el-descriptions-item>
            <el-descriptions-item label="订单状态"><el-tag :type="getStatusTagType(currentOrder.state)">{{ currentOrder.state }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="order-detail-user" style="margin-top: 20px;">
          <h3>收货信息</h3>
          <el-descriptions border column="2" :column="{ xs: 1, sm: 2 }">
            <el-descriptions-item label="联系人">{{ currentOrder.linkUser }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentOrder.linkPhone }}</el-descriptions-item>
            <el-descriptions-item label="联系地址" :span="2">{{ currentOrder.linkAddress }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="order-detail-goods" style="margin-top: 20px;">
          <h3>商品信息</h3>
          <el-table :data="orderGoods" style="width: 100%">
            <el-table-column prop="goodId" label="商品ID" width="100" />
            <el-table-column prop="goodName" label="商品名称" width="200" />
            <el-table-column prop="standard" label="商品规格" />
            <el-table-column prop="count" label="数量" width="100" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listOrders, getOrder, deleteOrders } from '@/api/order';
import { listOrderGoods } from '@/api/orderGoods';

// 表格数据
const orderList = ref({ records: [], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  state: ''
});
const dateRange = ref<Array<any>>([]);

// 详情对话框
const detailDialogVisible = ref(false);
const currentOrder = ref<any>(null);
const orderGoods = ref<Array<any>>([]);

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      orderNo: searchForm.orderNo || undefined,
      state: searchForm.state || undefined
    };
    
    // 添加日期范围搜索条件
    if (dateRange.value && dateRange.value.length === 2) {
      params.startTime = dateRange.value[0];
      params.endTime = dateRange.value[1];
    }
    
    const res = await listOrders(params);
    if (res.data.code === 200 && res.data.data) {
      orderList.value = res.data.data;
    }
  } catch (error) {
    ElMessage.error('加载订单列表失败');
    console.error('加载订单列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 根据订单状态获取标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case '待支付':
      return 'warning';
    case '已支付':
      return 'info';
    case '已发货':
      return 'primary';
    case '已完成':
      return 'success';
    case '已取消':
      return 'danger';
    default:
      // 使用info作为默认值，因为ElTag组件不支持'default'类型
      return 'info';
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  loadOrderList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = '';
  searchForm.state = '';
  dateRange.value = [];
  currentPage.value = 1;
  loadOrderList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadOrderList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadOrderList();
};

// 查看订单详情
const viewOrderDetail = async (row: any) => {
  try {
    // 获取订单详情
    const orderRes = await getOrder(row.id);
    if (orderRes.data.code === 200 && orderRes.data.data) {
      currentOrder.value = orderRes.data.data;
      
      // 获取订单商品列表
      const goodsRes = await listOrderGoods({ orderId: row.id });
      if (goodsRes.data.code === 200 && goodsRes.data.data.records) {
        // 为了获取商品名称，可能需要进一步调用商品API
        // 这里简化处理，实际项目中可能需要优化
        orderGoods.value = goodsRes.data.data.records;
      }
      
      detailDialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('加载订单详情失败');
    console.error('加载订单详情失败:', error);
  }
};

// 删除订单
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个订单吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const res = await deleteOrders([id]);
    if (res.data.code === 200) {
      ElMessage.success('删除成功');
      loadOrderList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error('删除失败:', error);
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadOrderList();
});
</script>

<style scoped>
.order-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-detail-info h3,
.order-detail-user h3,
.order-detail-goods h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}
</style>